package com.yumeng.framework.auth.security.userdetails;

import com.yumeng.framework.auth.bean.AuthExtDataInfo;
import com.yumeng.common.auth.BaseAuthInfo;
import com.yumeng.framework.auth.exception.NormalPermException;
import com.yumeng.framework.auth.security.bean.MyUserDetails;
import com.yumeng.framework.auth.service.auth.BaseAuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * 基础UserDetailsServiceImpl
 * @author wxd
 * @date 2025/4/11 15:58
 */
@Slf4j
public abstract class MyAbstractUserDetailsService {

    private BaseAuthService baseAuthService;

    public MyAbstractUserDetailsService(BaseAuthService baseAuthService) {
        this.baseAuthService = baseAuthService;
    }

    public UserDetails getUserDetailsByPrincipal(Object principal){
        log.debug("获取用户信息BaseUserDetailsServiceImpl:getUserDetailsByPrincipal-{}", principal);
        if (principal == null || StringUtils.isBlank(String.valueOf(principal))) {
            throw new InternalAuthenticationServiceException("未获取到有效主体身份信息");
        }
        //获取用户信息
        BaseAuthInfo authInfo = retrieveBaseAuthInfo(principal);
        if (authInfo == null) {
            String msg = String.format("未获取到用户信息：%s", principal);
            log.error(msg);
            throw new UsernameNotFoundException(msg);
        }
        if (StringUtils.isBlank(authInfo.getIdentityId())){
            throw new InternalAuthenticationServiceException(String.format("用户ID缺失：%s", authInfo.getAuthKey()));
        }
        /*        try{
            if (StringUtils.isBlank(authInfo.getIdentityId())){
                //此处异常一般不会触发，目的是排除catch异常
                throw new InternalAuthenticationServiceException(String.format("用户ID缺失：%s", username));
            }
        }catch (Exception e){
            log.error(String.format("用户信息获取失败：%s-%s", username, e.getMessage()), e);
            throw new InternalAuthenticationServiceException(String.format("用户信息获取失败：%s", username));
        }*/
        if (CollectionUtils.isEmpty(authInfo.getAuthorities())){
            String msg = String.format("用户权限不足：%s", authInfo.getAuthKey());
            log.error(msg);
            throw new NormalPermException(msg);
        }
        //获取扩展数据
        AuthExtDataInfo extDataInfo = baseAuthService.getAuthExtDataInfo(authInfo);
        if (extDataInfo != null) {
            authInfo.setDataMap(extDataInfo.getDataMap());
            authInfo.setLoginInfo(extDataInfo.getLoginInfo());
        }
        return new MyUserDetails(authInfo);
    }

    /**
     * 获取BaseAuthInfo
     * @param principal
     * @return
     */
    protected abstract BaseAuthInfo retrieveBaseAuthInfo(Object principal);

}
